<template>
    <div class="qilin-QilinWeb">
        <slot></slot>
        <!-- <el-button size="mini" plain icon="el-icon-monitor" >预览线上文件</el-button>
        <el-button size="mini" plain icon="el-icon-view" @click="previewFile()">预览本地文件</el-button> -->
        <el-button size="mini" plain icon="el-icon-download" @click="importButton()">导入</el-button>
        <el-button size="mini" plain icon="el-icon-upload2" @click="exportButton()">导出</el-button>
        <el-button size="mini" plain icon="el-icon-printer" v-print="printObj">打印</el-button>
        <el-button size="mini" plain icon="el-icon-bottom" @click="downloadButton()">下载模板</el-button>
        <el-button size="mini" plain icon="el-icon-edit-outline" @click="eSign()">电子签名</el-button>
        <el-button size="mini" plain @click="readFile()">读取文件内容</el-button>
        <el-upload 
            action="#" ref="upload" accept=".xlsx,.xls" :limit="1" 
            name="配合实现导入功能，该元素隐藏即可"
            :auto-upload="false" :on-change="changeXlsx"
        ></el-upload>
        <QilinDialog :dialogConfig.sync="dialogConfig" @handleClose="closeDialog"
            @submitConfirm="saveESign('esign')"
        >
            <div class="esign-box">
                <vue-esign ref="esign" :width="800" :height="400" 
                    :isCrop="eSignObj.isCrop"
                    :lineWidth="eSignObj.lineWidth" 
                    :lineColor="eSignObj.lineColor"
                    :bgColor.sync="eSignObj.bgColor" 
                ></vue-esign>
                <img v-if="eSignObj.resultImg" :src="eSignObj.resultImg" 
                    alt="电子签名照片" width="300px" height="150px"
                    style="border:1px dashed #e6e6e6;"
                >
            </div>
        </QilinDialog>
        <QilinDialog :dialogConfig.sync="previewConfig.dialogConfig" @handleClose="handleClosePreview">
            <el-upload action="#" :auto-upload="false" :on-change="changeFile" ref="previewUpload">
                <el-button type="primary" size="mini">选择文件</el-button>
                <span slot="tip" style="margin-left:10px;">选择文件后可直接预览各种格式的文件</span>
            </el-upload>
            <div v-show="previewConfig.previewLoading" style="width:100%;height:500px;overflow:auto;">正在加载中请稍后</div>
            <div v-show="!previewConfig.previewLoading" ref="previewBox" style="width:100%;height:500px;overflow:auto;"></div>
        </QilinDialog>
        <QilinDialog :dialogConfig.sync="readDialogConfig" @handleClose="handleCloseReadDialog">
            <el-upload action="#" :auto-upload="false" :on-change="changeReadFile" 
                ref="readFileUpload"
            >
                <el-button type="primary" size="mini">选择文件</el-button>
            </el-upload>
        </QilinDialog>
    </div>
</template>
<script>
/**
 * 本组件收藏真实项目遇到的各种操作示例代码
 */
import {readBuffer,render} from "@/views/study/skill/previewUtil.js";
import * as mammoth from "mammoth";
import {getDocument} from "pdfjs-dist";
import * as XLSX from "xlsx";
import Qilin from "qilin-utils";
export default {
    inject:["uploadImageUrl","uploadXlsxUrl"],
    data() {
        return {
            /**
             *  打印功能
             *     需要在main.js写如下代码（提前安装依赖--npm install vue-print-nb -S）
             *     import Print from "vue-print-nb";
             *     Vue.use(Print);
             */
            printObj: {
                //打印功能配置项
                id: "table",
                // popTitle:"打印数据",
                extraHead: `
                    <meta http-equiv="Content-Language" content="zh-cn" />,
                    <style>#table {width:100%;} </style>
                `,
            },
            /**
             * 电子签名功能
             *      需要在main.js写如下代码（提前安装依赖--npm install vue-esign -S）
             *      import vueEsign from "vue-esign";
             *      Vue.use(vueEsign);
             */
            eSignObj:{
                lineWidth:6,
                lineColor:"#000000",
                bgColor:"",
                resultImg:"",
                isCrop:false
            },
            dialogConfig:{
                title:"生成电子签名",
                isShow:false,
                additionalButton:[
                    {
                        btnText:"清空画板",
                        btnType:"default",
                        click:this.resetEsign
                    }
                ]
            },
            /**
             * 本地预览配置项
             */
            previewConfig:{
                dialogConfig:{ //本地预览库弹窗配置项
                    isShow:false,
                    title:"本地预览",
                    width:"70%"
                },
                previewLoading:false, //是否正在加载
                lastRender:null, //上个渲染实例
            },
            /**
             * 读取文件内容弹窗配置项
             */
            readDialogConfig:{
                isShow:false,
                title:"读取文件内容"
            }
        };
    },
    methods: {
        // 点击预览docx文件按钮事件监听
        previewFile(){
            this.previewConfig.dialogConfig.isShow=true;
        },
        handleClosePreview(){
            this.$refs["previewUpload"].clearFiles();
            this.previewConfig.lastRender.$destroy();
            this.previewConfig.dialogConfig.isShow=false;
        },
        // 点击选择文件事件监听
        async changeFile(file,fileList){
            // console.log(file,fileList);
            this.previewConfig.previewLoading=true;
            try{
                const arrayBuffer=await readBuffer(file.raw);
                this.previewConfig.previewLoading=false;
                this.previewConfig.lastRender=await this.displayResult(arrayBuffer,file.raw);
            }catch(e){
                console.log(e);
            }finally{
                this.previewConfig.previewLoading=false;
            }
        },
        // 渲染预览效果事件监听
        displayResult(buffer,file){
            const {name}=file; //获取文件名
            const extendType=name.substr(name.lastIndexOf(".")+1); //获取文件拓展名
            const {previewBox}=this.$refs; //获取输出DOM位置
            const newNode=document.createElement("div"); //生成新的DOM元素
            if(this.previewConfig.lastRender){ //添加子元素，防止vue实例替换DOM元素
                previewBox.removeChild(this.previewConfig.lastRender.$el);
                this.previewConfig.lastRender.$destroy();
            };
            const childDom=previewBox.appendChild(newNode);
            return new Promise((resolve,reject)=>{
                render(buffer,extendType,childDom).then(resolve).catch(reject);
            });
        },
        // 点击导入按钮事件监听
        importButton() {
            this.$refs['upload'].$children[0].$refs.input.click();
        },
        // 导入文件状态改变事件监听
        changeXlsx(file,fileList){
            console.log(file,fileList);
            // const xlsxType=file.name.split(".").pop();
            // if(!["xlsx","xls"].includes(xlsxType)){
            //     this.$message({
            //         message:"请上传正确格式的excel文档",
            //         type:"warning"
            //     });
            //     // this.$refs["upload"].uploadFiles.splice(0,1);
            //     // this.$refs["upload"].clearFiles();
            // }else{
            //     let formData=new FormData();
            //     if(this.activeName === "promotion"){
            //         formData.append("type",1);
            //     }
            //     formData.append("files",file.raw);
            //     importExcelData(formData).then((res)=>{
            //         if(res.code === 200){
            //             this.message({
            //                 message:"导入成功",
            //                 type:"success"
            //             });
            //             this.getTableData();
            //         }else{
            //             this.$message({
            //                 message:res.message || "导入失败",
            //                 type:"error"
            //             });
            //             // 返回失败后的xlsx文档说明，然后自动下载该失败说明xlsx文档
            //             let a=document.createElement("a");
            //             a.href=this.uploadImageUrl+res.result.fileUrl;
            //             a.download="错误模板.xlsx";
            //             a.style.display="none";
            //             document.body.appendChild(a);
            //             a.dispatchEvent(new MouseEvent("click"));
            //             a.remove();
            //             if(res.result.successCount && res.result.successCount > 0){
            //                 this.getTableData();
            //             }
            //         }
            //     });
            // }
            // // 导入时每次导入一个文件需要将其清空，方便下次导入
            // this.$refs["upload"].clearFiles();
        },
        // 点击导出按钮事件监听
        async exportButton(){
            /**
             * 该导出是将筛选条件传于后台，后台返回数据流文件，
             * 若希望下载下来得到是一个Blob对象，则须在ajax请求时指定responseType=blob，
             * 然后前端进行解析Blob对象转为xlsx文档
             */
            // 处理相关筛选条件
            // let params={};
            // // Object.keys(this.formSearch).forEach((item)=>{
            // //     if(this.formSearch[item]){
            // //         params[item]=this.formSearch[item];
            // //         if(typeof params[item] === "string"){
            // //             params[item]=params[item].trim();
            // //         }
            // //     }
            // // });
            // // if(params.date && params.date.length>0){
            // //     params.startYear=params.date[0];
            // //     params.lastYear=params.date[1];
            // //     Reflect.deleteProperty(params,"date");
            // // }
            // let result,xlsxName;
            // let getResult = async (fn,params)=>{
            //     return await fn(params).then((res)=>{
            //         return res;
            //     });
            // }
            // if(this.activeName === "promotion"){
            //     result=await getResult(exportExcelPromotionData,params);
            //     xlsxName="P职级晋升调整总表.xlsx";
            // }else if(this.activeName === "achievements"){
            //     result=await getResult(exportExcelAchievementsData,params);
            //     xlsxName="绩效积分.xlsx";
            // }else if(this.activeName === "qualifications"){
            //     result=await getResult(getQualificationsData,params);
            //     xlsxName="资质积分.xlsx";
            // }else if(this.activeName === "innovate"){
            //     result=await getResult(getInnovateData,params);
            //     xlsxName="创新积分.xlsx";
            // }else if(this.activeName === "contribution"){
            //     result=await getResult(getContributionData,params);
            //     xlsxName="贡献积分.xlsx";
            // }
            // if(result){
            //     var blob = new Blob([result], {
            //         type:"application/vnd.ms-excel;charset=UTF-8",
            //     });
            //     if (window.navigator.msSaveBlob) {//没有此判断的话，ie11下的导出没有效果
            //         //    window.navigator.msSaveBlob(blob, unescape(res.headers.filename.replace(/\\u/g, '%u')));
            //         window.navigator.msSaveBlob(blob,xlsxName);
            //     } else {
            //         var downloadElement = document.createElement("a");
            //         var href = window.URL.createObjectURL(blob); //创建下载的链接
            //         downloadElement.href = href;
            //         downloadElement.download = xlsxName;
            //         document.body.appendChild(downloadElement);
            //         downloadElement.click(); //点击下载
            //         document.body.removeChild(downloadElement); //下载完成移除元素
            //         window.URL.revokeObjectURL(href); //释放掉blob对象
            //     }
            // }
        },
        // 点击下载模板按钮事件监听
        downloadButton() {
            /**
             * 下载图片方法
             */
            // 方法一--（问题是项目地址的域名和图片地址要相同，否则点击下载当前页会变成图片地址）
            // let a=document.createElement("a");
            // a.href=this.uploadImageUrl+"image-1657605816411.jpeg";
            // a.download="文件模板";
            // a.style.display="none";
            // document.body.appendChild(a);
            // a.dispatchEvent(new MouseEvent("click"));
            // a.remove();
            // 方法二--（解决方法一的问题）
            const image = new Image();
            // 解决跨域 Canvas 污染问题
            image.setAttribute("crossOrigin", "anonymous");
            image.src = this.uploadImageUrl+"image-1657605816411.jpeg";
            image.onload = () => {
                const canvas = document.createElement("canvas");
                canvas.width = image.width;
                canvas.height = image.height;
                const context = canvas.getContext("2d");
                context.drawImage(image, 0, 0, image.width, image.height);
                canvas.toBlob((blob) => {
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement("a");
                    a.download = "tupian.jpg";
                    a.href = url;
                    a.click();
                    a.remove();
                    URL.revokeObjectURL(url);
                });
            };
            /**
             * 下载xlsx模板文件
             */
            
            // 方法一
            // let a=document.createElement("a");
            // switch (this.activeName) {
            //     case "promotion" :
            //         a.href=this.uploadXlsxUrl+"P职级晋升调整导入表.xls";
            //         break;
            //     case "achievements":
            //         a.href=this.uploadXlsxUrl+"绩效积分导入表.xls";
            //         break;
            //     case "qualifications":
            //         a.href=this.uploadXlsxUrl+"资质积分导入表.xls";
            //         break;
            //     case "innovate":
            //         a.href=this.uploadXlsxUrl+"创新积分导入表.xls";
            //         break;
            //     case "contribution":
            //         a.href=this.uploadXlsxUrl+"贡献积分导入表.xls";
            //         break;
            // }
            // a.download="文件模板.xlsx";
            // a.style.display="none";
            // document.body.appendChild(a);
            // a.dispatchEvent(new MouseEvent("click"));
            // a.remove();

            // 方法二
            // const iframe=document.createElement("iframe");
            // iframe.src=this.uploadXlsxUrl+"P职级晋升调整导入表.xls";
            // iframe.style.display="none";
            // iframe.style.height=0;
            // document.body.appendChild(iframe);
            // setTimeout(()=>{
            //     document.body.removeChild(iframe);
            // },2000);
        },
        /**
         * 电子签名逻辑区域
         */
        // 点击电子签名按钮事件监听
        eSign(){
            this.dialogConfig.isShow=true;
        },
        // 点击关闭弹窗事件监听
        closeDialog(){
            this.dialogConfig.isShow=false;
            this.resetEsign();
        },
        // 清空画板
        resetEsign(){
            this.eSignObj.resultImg="";
            this.$refs["esign"].reset();
        },
        // 保存电子签名图片
        saveESign(refName){
            this.$refs[refName].generate().then((res)=>{
                // console.log(res);
                this.eSignObj.resultImg=res;
            }).catch((err)=>{
                console.log("请签名");
            });
        },
        /**
         * 读取文件内容逻辑区域
         */
        // 点击读取文件内容按钮事件监听
        readFile(){
            this.readDialogConfig.isShow=true;
        },
        // 读取文件内容弹窗关闭事件监听
        handleCloseReadDialog(){
            this.readDialogConfig.isShow=false;
        },
        // 选择文件事件监听
        changeReadFile(file,fileList){
            // console.log(file,fileList);
            const index=file.name.lastIndexOf(".");
            const fileType=file.name.slice(index+1);
            if(["docx","doc"].includes(fileType)){
                const reader=new FileReader();
                reader.onload=(e)=>{
                    const arrayBuffer=e.target.result;
                    mammoth.extractRawText({
                        arrayBuffer:arrayBuffer
                    }).then((res)=>{
                        const content=res.value;
                        console.log(content.trim().split("\n"));
                        console.log(Qilin.String.trimString(content,false).split("\n"));
                        console.log(Qilin.String.trimString(content,true).split("\n"));
                    });
                };
                reader.readAsArrayBuffer(file.raw);
            }else if(["pdf"].includes(fileType)){
                const reader=new FileReader();
                reader.onload = async (e) => {
                    const arrayBuffer = e.target.result;
                    console.log(e)
                    const pdf = await getDocument({ data: arrayBuffer }).promise;
                    const numPages = pdf.numPages;
                    let content = "";

                    for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
                        const page = await pdf.getPage(pageNumber);
                        const textContent = await page.getTextContent();
                        const pageContent = textContent.items.map((item) => item.str).join(" ");
                        content += pageContent + "\n"; // 每页内容以换行符分隔
                    }
                    console.log(content.trim().split("\n"));
                    console.log(Qilin.String.trimString(content,false).split("\n"));
                    console.log(Qilin.String.trimString(content,true).split("\n"));
                    // 进一步处理 PDF 文件内容
                };
                reader.readAsArrayBuffer(file.raw);
            }else if(["xls","xlsx"].includes(fileType)){
                const reader = new FileReader();
                reader.onload = (e) => {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: "array" });
                    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

                    console.log(jsonData);
                    // 进一步处理 Excel 文件内容
                };
                reader.readAsArrayBuffer(file.raw);
            };
        }
    },
    mounted(){
        
    }
};
</script>
<style lang="less" scoped>
.qilin-QilinWeb {
    text-align: right;
    padding:0 0 10px 0;
    > .el-button {
        border-radius: 2px;
        margin-bottom:5px;
        &:nth-child(1) {
            background: rgba(86, 206, 163, 0.14);
            color: #56cea3;
            border: 1px solid #56cea3;
        }
        &:nth-child(2) {
            background: rgba(250, 173, 20, 0.15);
            border: 1px solid #faad14;
            color: #faad14;
        }
        &:nth-child(3) {
            background: rgba(20, 142, 255, 0.14);
            border: 1px solid #148eff;
            color: #148eff;
        }
        &:nth-child(4) {
            background: rgba(155, 152, 255, 0.14);
            border: 1px solid #9b98ff;
            color: #9b98ff;
        }
        &:nth-child(5) {
            background: rgba(240, 130, 29, 0.14);
            border: 1px solid #f0821d;
            color: #f0821d;
        }
        &:nth-child(6) {
            background: rgba(240, 130, 29, 0.14);
            border: 1px solid #f0821d;
            color: #f0821d;
        }
        &:nth-child(7) {
            background: rgba(240, 130, 29, 0.14);
            border: 1px solid #f0821d;
            color: #f0821d;
        }
        &:nth-child(8) {
            background: rgba(240, 130, 29, 0.14);
            border: 1px solid #f0821d;
            color: #f0821d;
        }
        &:nth-child(9) {
            background: rgba(240, 130, 29, 0.14);
            border: 1px solid #f0821d;
            color: #f0821d;
        }
        &:nth-child(10) {
            background: rgba(240, 130, 29, 0.14);
            border: 1px solid #f0821d;
            color: #f0821d;
        }
        &:nth-child(11) {
            background: rgba(240, 130, 29, 0.14);
            border: 1px solid #f0821d;
            color: #f0821d;
        }
        &:nth-child(12) {
            background: rgba(240, 130, 29, 0.14);
            border: 1px solid #f0821d;
            color: #f0821d;
        }
    }
    >div,.el-upload{
        display:none;
    }
}
.esign-box{
    border:2px solid @color-border;
    text-align:center;
}
</style>
// 打印样式设置
<style media="print">
@page {
    size: auto;
    margin: 3mm;
}
/**
    @media print只影响打印的样式，不会影响页面样式
*/
@media print {
    html {
        background-color: #ffffff;
        height: auto;
        margin: 0px;
    }
    body {
        border: solid 1px #ffffff;
        /* margin: 10mm 15mm 10mm 15mm; */
    }
    /**
        table是el-table元素的id
    */ 
    #table table {
        table-layout: auto !important;
    }
    #table .el-table__header-wrapper .el-table__header {
        width: 100% !important;
        border: solid 1px #f2f2f2;
    }
    #table .el-table__body-wrapper .el-table__body {
        width: 100% !important;
    }
    /* #table table {
    table-layout: fixed !important;
  } */
}
</style>